from rest_framework import serializers
from .models import ExperimentPlan
from personnel.models import Equipment


class ExperimentPlanSerializer(serializers.ModelSerializer):
    """试验计划序列化器"""
    equipment_name = serializers.CharField(source='equipment.name', read_only=True)
    equipment_responsible = serializers.CharField(source='equipment.responsible', read_only=True)
    
    class Meta:
        model = ExperimentPlan
        fields = [
            'id', 'experiment_type', 'equipment', 'equipment_name', 'equipment_responsible',
            'enter_date', 'start_date', 'complete_date', 'end_date',
            'source', 'is_adjustable', 'project', 'depart', 'days', 'bid', 'addr', 'details',
            'experiment_report_name', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def validate(self, data):
        """验证时间逻辑"""
        enter_date = data.get('enter_date')
        start_date = data.get('start_date')
        complete_date = data.get('complete_date')
        end_date = data.get('end_date')
        
        if enter_date and start_date and enter_date > start_date:
            raise serializers.ValidationError("开始时间不能早于入场时间")
        
        if start_date and complete_date and start_date > complete_date:
            raise serializers.ValidationError("完成时间不能早于开始时间")
        
        if complete_date and end_date and complete_date > end_date:
            raise serializers.ValidationError("出场时间不能早于完成时间")
        
        return data


class ExperimentPlanCreateSerializer(serializers.ModelSerializer):
    """试验计划创建序列化器（用于外部系统数据导入）"""
    equipment_name = serializers.CharField(write_only=True)
    
    class Meta:
        model = ExperimentPlan
        fields = [
            'experiment_type', 'equipment_name',
            'enter_date', 'start_date', 'complete_date', 'end_date',
            'source', 'is_adjustable', 'project', 'depart', 'days', 'bid', 'addr', 'details'
        ]
    
    def create(self, validated_data):
        equipment_name = validated_data.pop('equipment_name')
        
        # 获取或创建设备
        equipment, created = Equipment.objects.get_or_create(
            name=equipment_name,
            defaults={'responsible': ''}
        )
        
        validated_data['equipment'] = equipment
        return super().create(validated_data)
    
    def validate(self, data):
        """验证时间逻辑"""
        enter_date = data.get('enter_date')
        start_date = data.get('start_date')
        complete_date = data.get('complete_date')
        end_date = data.get('end_date')
        
        if enter_date and start_date and enter_date > start_date:
            raise serializers.ValidationError("开始时间不能早于入场时间")
        
        if start_date and complete_date and start_date > complete_date:
            raise serializers.ValidationError("完成时间不能早于开始时间")
        
        if complete_date and end_date and complete_date > end_date:
            raise serializers.ValidationError("出场时间不能早于完成时间")
        
        return data


class ExperimentPlanListSerializer(serializers.ModelSerializer):
    """试验计划列表序列化器（用于前端甘特图显示）"""
    equipment_name = serializers.CharField(source='equipment.name', read_only=True)
    equipment_responsible = serializers.CharField(source='equipment.responsible', read_only=True)
    
    # 前端需要的字段映射
    enter = serializers.DateField(source='enter_date', read_only=True)
    start = serializers.DateField(source='start_date', read_only=True)
    complete = serializers.DateField(source='complete_date', read_only=True)
    end = serializers.DateField(source='end_date', read_only=True)
    equipment = serializers.CharField(source='equipment.name', read_only=True)
    
    class Meta:
        model = ExperimentPlan
        fields = [
            'id', 'experiment_type', 'equipment', 'equipment_name', 'equipment_responsible',
            'enter', 'start', 'complete', 'end', 'enter_date', 'start_date', 'complete_date', 'end_date',
            'source', 'is_adjustable', 'project', 'depart', 'days', 'bid', 'addr', 'details',
            'experiment_report_name'
        ]